package com.acme.bankapp.service.bank;

import com.acme.bankapp.domain.bank.Email;

public class EmailService implements Runnable {
	private Queue<Email> emailQueue = new Queue<>();
	private boolean toBeClosed = false;
	private Thread emailServiceThread;
	
	public EmailService () {
	}

	public void start() {
		emailServiceThread = new Thread(this);
		emailServiceThread.start();
	}
	
	@Override
	public void run() {
			try {
				while (true) {
					sendEmail(emailQueue.pop());
					Thread.sleep(1000);
				}
			} catch (InterruptedException e) {
				while (!emailQueue.isEmpty()) {
					sendEmail(emailQueue.pop());
					try {Thread.sleep(1000);} catch (InterruptedException e1) {e1.printStackTrace();}
				}
			}
	}

	private void sendEmail(Email msg) {
		System.out.println("Email sent "+msg.toString());
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void addEmailToQueue(Email msg) {
		emailQueue.push(msg);
	}
	public void stop () {
		toBeClosed = true;
		emailServiceThread.interrupt();
	}

}
